#include "stdafx.h"
#include "BufferStream.h"
#include "Utils.h"

BufferOutStream::BufferOutStream(int nSize)
{
	mData = NULL;
	mSize = nSize;
	mbFree = 1;
	if( mSize>0 ) mData= new char[nSize];
}
BufferOutStream::~BufferOutStream(void)
{
	Release();
}
void BufferOutStream::Attach(int nSize)
{
	Release();
	mSize = nSize;
	mbFree = 1;
	if( mSize>0 ) mData= new char[nSize];
}
void BufferOutStream::Attach(char * buffer,int nSize)
{
	Release();
	mData = buffer;
	mSize = nSize;
}

void BufferOutStream::Release()
{
	if( mbFree) {
		if( mData ) delete[] mData;
		mData = NULL;
		mSize = 0;
	}
	mbFree =0;
}
StringOutter::StringOutter()
{
	mLast = 0;
}
void StringOutter::Clear()
{
	memset(mData,0,mSize); 
	mLast =0;
}
void StringOutter::PutQ(const char * p)
{
	int i = strlen(p);
	if( (mLast+i)>=mSize ) return ;
	strcpy(mData+mLast,p);
	mLast +=i;
}
void StringOutter::Put(const char * fmt,...)
{
	va_list va_ap;
	va_start (va_ap, fmt);
	mLast +=vsnprintf(mData+mLast, mSize-mLast, fmt, va_ap);
	va_end(va_ap);
}
KeyPairOutter::KeyPairOutter()
{
}
KeyPairOutter::~KeyPairOutter()
{
}
void KeyPairOutter::PutKey(const char *key, const char *value,char conn)
{
   mData[mLast++]=' ';
   mData[mLast++]='"';
   strcpy(mData+mLast,key);
   mLast += strlen(key);
   mData[mLast++]='"';
   mData[mLast++]=conn;
   strcpy(mData+mLast,value);
   mLast += strlen(value);
}
void KeyPairOutter::PutKeyQ(const char *key, const char *value,char conn)
{
   mData[mLast++]=' ';
   mData[mLast++]='"';
   strcpy(mData+mLast,key);
   mLast += strlen(key);
   mData[mLast++]='"';
   mData[mLast++]=conn;
   mData[mLast++]='"';
   strcpy(mData+mLast,value);
   mLast += strlen(value);
   mData[mLast++]='"';
}
void KeyPairOutter::PutKeyEncode(const char *key, const char *value,char conn)
{
   mData[mLast++]=' ';
   mData[mLast++]='"';
   mLast += Utils::json_escape_str(mData+mLast,key);
   mData[mLast++]='"';
   mData[mLast++]=conn;
   mLast += Utils::json_escape_str(mData+mLast,value);
}